import json
import time

import requests
from numpy import random

from app.modules1.PublicApproach import get_token_result, get_last_month_range, _get_vendor_ids_from_db
from app.modules1.common.encryptionUtils import getResult1


def _fetch_paginated_realSales_data():
    """分页获取采购出入库明细数据"""
    print("[DEBUG] _fetch_paginated_purchase_data() 函数开始执行")
    # 获取token
    token = get_token_result()
    print(f"[DEBUG] 获取到token: {token[:20] if token else 'None'}...")

    # 获取日期
    start_date, end_date = get_last_month_range()
    print(f"[DEBUG] 查询日期范围: {start_date} 到 {end_date}")

    # 获取实销实结、OEM实销实结供应商
    vendor_ids_str = _get_vendor_ids_from_db("实销实结,OEM实销实结")
    print(f"[DEBUG] 获取到供应商ID: {vendor_ids_str}")

    url = "https://web.jackyun.com/jkyun/erp/purchorder/getpurchoutinwarehouseinfo"
    base_header = {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "module_code": "mainframe",
        "origin": "https://web.jackyun.com",
        "referer": "https://web.jackyun.com/home/mainframe_web.html",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "Windows",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.5359.125 Safari/537.36",
        "x-requested-with": "XMLHttpRequest",
    }
    all_purchase_details = []
    page_index = 0
    page_size = 1000
    session = requests.Session()  # 使用 Session 保持连接
    # 去掉一件代发仓
    warehouseIds = "1336070890133324544,743255118019625856,743255118128677760,1417239991126099712,1986443614567170560,2068841910925919232,1920407559764902400,1964561067655692800,2208016583559939456,2202392778890937856,2200186645209351040,2200186641166041984,2200186632039236480,2200186636594250624,2200186627115123584,2200186620437791616,2200186612082738048,2200186603778016128,2187742358607823104,2187694686379836544,2181416842340533888,2181416325770053248,2173325962101293952,2170479451046217472,2170432319370724608,2170307271536740096,2158943111372244224,2158942078266836096,2158930682542195968,2158927911986300160,2148746470579437824,2128314708271105792,2124676649520923776,2122534243312797696,2122494971476248192,2120649486729381120,2112540702796873984,2109664993634814464,2103041129078129920,2101003695678195072,2099523790783284608,2093503182696286080,2092786234173489920,2092039419363264256,2091497826654815232,2087076535149167360,2083500816324167040,2083500466602148992,2083498984839774592,2082738907052311936,2082107296143705344,2081232078274200064,2073928802906276608,2073406285774981120,2071923154067817088,2069089932444338048,2068254008513725056,2064942437610357248,2060854904866374144,2058939255752558464,2056569698050279552,2048636352525961472,2048094649792529024,2047317693519792128,2043443863122937728,2039289456388540288,2039200520004863872,2037735172584833408,2036967797411448704,2032594137851495296,2030767087823292288,2029400904921155072,2029200573546170112,2029173442505246208,2029125719866672000,2028417987521609984,2026920165257315968,2026303999190107008,2023963651698001536,2018222206859740160,2017836176524575744,2017438930167531392,2016159862624256896,2015228285811589376,2014630275881797376,2012823398366642688,2012819020383682816,2005407668229768320,2005396093774660224,2004663147954080000,2002168044857919872,1992969049087017600,1989986473105098880,1987813258947789056,1986448481069106304,1986445822683677184,1985680223205458688,1984253834350723968,1977098091512071296,1970325698298316032,1967424274042127232,1967398617954321280,1967371151917515136,1966734138831406208,1955858059988207488,1955064187267745664,1950827615111807744,1947206852520313984,1946558060365153536,1942127174206949632,1940604795937293184,1938499502388184576,1921679199118885504,1921678607822684800,1921678013380756096,1921676447070880000,1737602652568126976,1633949968465756800,1627522238705140992,1194223064054530432"
    print("开始获取采购出入库明细数据...")
    while True:
        header = base_header.copy()
        header["authorization"] = f"Bearer {token}"

        data_payload = {
            "getType": "1",
            "billNos": "",
            "queryDateType": "2",
            "timeType": "3",
            "startTime": start_date,
            "endTime": end_date,
            "isQuickSearch": "0",
            "inouttype": "",
            "skuIds": "",
            "brandId": "",
            "vendIds": str(vendor_ids_str),
            "cateIds": "",
            "warehouseIds": warehouseIds,
            "companyId": "1924002902255536000",  # 新疆最西域电子商务有限公司
            "settStatus": "",
            "paidStatus": "",
            "applyUserName": "",
            "busiName": "",
            "purchOfficeName": "",
            "memo": "",
            "isHideWriteOffBill": "0",
            "archived": "0",
            "pageIndex": str(page_index),
            "pageSize": str(page_size),
            "sortField": "",
            "sortOrder": "",
            "cols": '["goodsdocNo","trDate","orderDate","vendId","vendName","orderNum","goodsNo","goodsName","skuName","quantity","taxPrice","payableAmount","unitName","currencyName","abbreviation","currencyRate","vendOrderId","recDate","isCertified","noTaxPrice","noTaxAmount","taxAmount","settStatus","paidStatus","batchNo","serialNo","companyName","orderCompanyName","purchOfficeName","busiName","applyUserName","comment","rowRemark","inOutMemo","orderMemo","orderDetailRemark","warehouseName","cateName","brandName","skuBarcode","inouttype"]',
        }

        try:
            requests_data = getResult1(token, data_payload)
            response = session.post(
                url,
                headers=header,
                data=requests_data,
                timeout=(10, 30),
                proxies={"http": None, "https": None},
            )

            if response.status_code != 200:
                print(f"请求失败，状态码: {response.status_code}")
                print(f"错误响应头: {response.headers}")
                try:
                    error_detail = response.json()
                    print(
                        f"错误详情: {json.dumps(error_detail, ensure_ascii=False, indent=2)}"
                    )
                except json.JSONDecodeError:
                    print(f"错误响应内容: {response.text}")
                break  # 请求失败则停止

            print(f"正在获取第 {page_index + 1} 页数据...")
            result = response.json()
            current_page_data = result.get("result", {}).get("data", [])

            if not current_page_data:  # 如果当前页没有数据
                print("没有更多数据了")
                break

            all_purchase_details.extend(current_page_data)
            print(f"当前页获取 {len(current_page_data)} 条数据")
            print(f"累计已获取 {len(all_purchase_details)} 条数据")

            # 添加随机延迟
            delay = random.uniform(1.2, 4.0)
            print(f"等待: {delay:.1f} 秒后继续...")
            time.sleep(delay)
            page_index += 1  # 准备获取下一页

        except requests.exceptions.RequestException as e:
            print(f"请求过程中发生错误: {e}")
            break  # 网络或请求错误也停止
        except Exception as e:
            print(f"处理响应时发生未知错误: {e}")
            break  # 其他未知错误

    session.close()  # 关闭 session
    print(f"[DEBUG] 数据获取完成，总共获取 {len(all_purchase_details)} 条数据")
    # 保存数据到数据库
    print("[DEBUG] 开始调用 _save_purchase_details_to_db()")
    # result = _save_purchase_details_to_db(all_purchase_details)
    print(f"[DEBUG] _save_purchase_details_to_db() 执行完成，返回值: {result}")
    return result


if __name__ == '__main__':
    _fetch_paginated_realSales_data()
